import base64, hashlib, json, os, time
from .abstract import ContentRecognizer
from .. import hmacSha256
ALGORITHM = 'TC3-HMAC-SHA256'
SERVICE = 'ocr'
HOST = f'{SERVICE}.tencentcloudapi.com'
SECRETID = 'AKIDXzsY2WKsPAZu5CJuRtGVfmkJaeTDOttr'
SECRETKEY = 'ISRJ6vW1W1jLoJ6nYDm7UcWN5Ym2D8oG'
URL = f'https://{HOST}/'
#OCR识别器类
class TencentOcrRecognizer(ContentRecognizer):
    def hash_sha256(self, data):
        # hash sha256加密
        sha256 = hashlib.sha256()
        sha256.update(data.encode())
        return sha256.hexdigest()
    def getHeaders(self, requestPayload):
        # 生成请求头部信息
        timestamp = int(time.time())
        gmTime = time.gmtime(timestamp)
        date = time.strftime('%Y-%m-%d', gmTime)
        credentialScope = f'{date}/{SERVICE}/tc3_request'
        canonicalHeaders = {
          'Content-Type': 'application/json; charset=utf-8',
          'Host': HOST
        }
        canonicalHeaderKeys = sorted(canonicalHeaders.keys())
        canonicalRequest = 'POST\n/\n\n'
        for key in canonicalHeaderKeys:
            canonicalRequest += f'{key.lower()}:{canonicalHeaders[key]}\n'
        signedHeaders = ';'.join(canonicalHeaderKeys).lower()
        canonicalRequest += f'\n{signedHeaders}\n'
        canonicalRequest += self.hash_sha256(requestPayload)
        stringToSign = f'{ALGORITHM}\n{timestamp}\n{credentialScope}\n' + self.hash_sha256(canonicalRequest)
        secretDate = hmacSha256.HMACSha256(f'TC3{SECRETKEY}'.encode(), date.encode()).digest()
        secretService = hmacSha256.HMACSha256(secretDate, SERVICE.encode()).digest()
        secretSigning = hmacSha256.HMACSha256(secretService, 'tc3_request'.encode()).digest()
        signature = hmacSha256.HMACSha256(secretSigning, stringToSign.encode()).hexdigest()
        return {
          'X-TC-Action': 'GeneralBasicOCR',
          'X-TC-Timestamp': f'{timestamp}',
          'X-TC-Version': '2018-11-19',
          'X-TC-Region': 'ap-guangzhou',
          'Authorization': f'{ALGORITHM} Credential={SECRETID}/{credentialScope}, SignedHeaders={signedHeaders}, Signature={signature}',
          **canonicalHeaders
        }
    #识别接口
    def onRecog(self, imgData):
        #imgData: 带有文件头部信息的二进制位图数据
        data = {'ImageBase64': base64.b64encode(imgData).decode()}
        requestPayload = json.dumps(data)
        res = self.post(URL, requestPayload.encode(), headers = self.getHeaders(requestPayload))
        if not res:return
        # 开始解析数据
        res = res['Response']
        if not res:return
        if 'Error' in res.keys():
            error = res['Error']
            raise Exception(f'{error["Code"]}: {error["Message"]}')
        lines = {}
        for textDetection in res['TextDetections']:
            info = json.loads(textDetection['AdvancedInfo'])
            parag = info['Parag']
            paragNo = parag['ParagNo']
            if not paragNo in lines.keys():
                lines[paragNo] = []
            words = lines[paragNo]
            detectedText, polygon, itemPolygon = textDetection['DetectedText'], textDetection['Polygon'], textDetection['ItemPolygon']
            words.append({'x': itemPolygon['X'], 'y': itemPolygon['Y'], 'width': itemPolygon['Width'], 'height': itemPolygon['Height'], 'text': detectedText})
        return lines.values()
    def onCancel(self):pass
